package com.transitup.gui.client;

//import com.google.appengine.repackaged.org.apache.commons.logging.impl.Log4JLogger;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;

import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;

import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Transitup implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final GreetingServiceAsync greetingService = GWT
			.create(GreetingService.class);

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		
//		RootPanel.get("table").setVisible(false);
		final List<String> requests = new ArrayList<String>();
		final IncrementableInteger requestId = new IncrementableInteger(0);
		final TextArea input = new TextArea();
		final TextArea output = new TextArea();
		final ListBox from = new ListBox();
		final ListBox to = new ListBox();
		final Image robot = new Image();
		final Label label = new Label("loading available languages from google translate");
		RootPanel.get("loading").add(label);
		robot.setUrl("Robot_walks.JPG");
		input.setPixelSize(400, 300);
		output.setPixelSize(400, 300);
		
		
		 
//		List<String> langArray = null;//{"af","sq","am","ar","hy","az","eu","be","bn","bh","bg","my","ca","chr","zh","zh-CN","zh-TW","hr","cs","da","dv","nl","en","eo","et","tl","fi","fr","gl","ka","de","el","gn","gu","iw","hi","hu","is","id","iu","ga","it","ja","kn","kk","km","ko","ku","ky","lo","lv","lt","mk","ms","ml","mt","mr","mn","ne","no","or","ps","fa","pl","pt","pa","ro","ru","sa","sr","sd","si","sk","sl","es","sw","sv","tg","ta","tl","te","th","bo","tr","uk","ur","uz","ug","vi","cy","yi"};
//		String[] langDisplayArray = {"Afrikaans","Albanian","Amharic","Arabic","Armenian","Azerbaijani","Basque","Belarusian","Bengali","Bihari","Bulgarian","Burmese","Catalan","Cherokee","Chinese","Chinese simplified","Chinese traditional","Croatian","Czech","Danish","Dhivehi","Dutch","English","Esperanto","Estonian","Filipino","Finnish","French","Galacian","Georgian","German","Greek","Guarani","Gujarati","Hebrew","Hindi","Hungarian","Icelandic","Indonesian","Inuktitut","Irish","Italian","Japanese","Kannada","Kazakh","Khmer","Korean","Kurdish","Kyrgyz","Laothian","Latvian","Lithuanian","Macedonian","Malay","Malayalam","Maltese","Marathi","Mongolian","Nepali","Norwegian","Oriya","Pashto","Persian","Polish","Portuguese","Punjabi","Romanian","Russian","Sanskrit","Serbian","Sindhi","Sinhalese","Slovak","Slovenian","Spanish","Swahili","Swedish","Tajik","Tamil","Tagalog","Telugu","Thai","Tibetan","Turkish","Ukranian","Urdu","Uzbek","Uighur","Vietnamese","Welsh","Yiddish"};

		greetingService.getAvailableLanguages(
		new AsyncCallback<List<List<String>>>() {

			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				
			}

			public void onSuccess(List<List<String>> result) {
				for(int i=0;i<result.get(0).size();i++)
				{
					from.addItem(result.get(1).get(i),result.get(0).get(i));
					to.addItem(result.get(1).get(i),result.get(0).get(i));
				}
				from.setSelectedIndex(result.get(0).indexOf("fr"));
				to.setSelectedIndex(result.get(0).indexOf("en"));
//				RootPanel.get("loading").setVisible(false);
				label.setText("");
//				RootPanel.get("table").setVisible(true);
				RootPanel.get("inputFieldContainer").add(input);
				RootPanel.get("outputFieldContainer").add(output);
				RootPanel.get("fromListContainer").add(from);
				RootPanel.get("toListContainer").add(to);
				RootPanel.get("robot").add(robot);
				RootPanel.get("inputLabel").add(new Label("Enter text to translate:"));
			}});
		
			
		
		// Focus the cursor on the name field when the app loads
		input.setFocus(true);
//		nameField.selectAll();

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label textToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
//		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
		dialogVPanel.add(textToServerLabel);
//		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
//		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
//				sendButton.setEnabled(true);
//				sendButton.setFocus(true);
			}
		});

		// Create a handler for the sendButton and nameField
		class MyHandler implements /*ClickHandler,*/ KeyUpHandler, ChangeHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
//			public void onClick(ClickEvent event) {
//				if(event.getSource().equals(from) || event.getSource().equals(to))
//				{
//					robot.setUrl("Robot_walks.JPG");
//					requests.removeAll(requests);
//				}
//				sendTransReq(event.getSource().equals(output));
//			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
//				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					sendTransReq(event.getSource().equals(output));
//				}
			}

			public void onChange(ChangeEvent event) {
				// TODO Auto-generated method stub
				sendTransReq(event.getSource().equals(output));
			}
			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void sendTransReq(boolean inverted) {
//				sendButton.setEnabled(false);
				if((inverted && (output.getText()==null || output.getText().length()==0))
						||(!inverted && (input.getText()==null || input.getText().length()==0))) 
					return;
				requests.add(requestId.increment().toString());
				robot.setUrl("Robot_walks.gif");
				final boolean invert=inverted;
				String textToServer = invert?output.getText():input.getText();
				String fromLang = invert?to.getValue(to.getSelectedIndex()):from.getValue(from.getSelectedIndex());
				String toLang = invert?from.getValue(from.getSelectedIndex()):to.getValue(to.getSelectedIndex());
//				textToServerLabel.setText(textToServer);
//				serverResponseLabel.setText("");
				try {
					greetingService.greetServer(textToServer,
							fromLang,toLang,requestId,
							new AsyncCallback<Result>() {
								public void onFailure(Throwable caught) {
									// Show the RPC error message to the user
									if(caught.getMessage().contains("[404]"))
									{
										robot.setUrl("Robot_walks.JPG");
										requests.removeAll(requests);
										return;
									}
									dialogBox
											.setText("Remote Procedure Call - Failure "+caught.getMessage());
									serverResponseLabel
											.addStyleName("serverResponseLabelError");
									serverResponseLabel.setHTML(caught.getMessage());
									dialogBox.center();
									robot.setUrl("Robot_walks.JPG");
									requests.removeAll(requests);
									closeButton.setFocus(true);
								}

								public void onSuccess(Result result) {
									
									if(requests.size()==0)
										return;
									requests.remove(String.valueOf(result.getId().getInteger()));
									if(requests.size()==0)
										robot.setUrl("Robot_walks.JPG");
									System.out.println(requests.size());
									if(result!=null)
									{
										if(invert)
											input.setText(result.getResult());
										else 
											output.setText(result.getResult());
									}
									
								}
							});
				} catch (Exception e) {
					dialogBox
					.setText("Result is null, All pending changes ("+requests.size()+" in total) will be dicarded");
					serverResponseLabel
							.addStyleName("serverResponseLabelError");
					serverResponseLabel.setHTML(SERVER_ERROR);
					dialogBox.center();
					robot.setUrl("Robot_walks.JPG");
					requests.removeAll(requests);
					closeButton.setFocus(true);
				}
			}

			

			
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
//		sendButton.addClickHandler(handler);
		input.addKeyUpHandler(handler);
		output.addKeyUpHandler(handler);
//		input.addClickHandler(handler);
//		output.addClickHandler(handler);
		from.addChangeHandler(handler);
		to.addChangeHandler(handler);
//		from.addClickHandler(handler);
//		to.addClickHandler(handler);
		
	}
	
//	public static void main(String[] args)
//	{
//		System.out.print("{");
//		for(int i=0;i<Language.values().length;i++)
//		{
//			System.out.print("\""+Language.values()[i]+"\",");
//		}
//		System.out.println("}");
//		System.out.print("{");
//		for(int i=0;i<Language.values().length;i++)
//		{
//			String displayName = Language.values()[i].name().replace('_', ' ').toLowerCase();
//			displayName = String.valueOf(displayName.charAt(0)).toUpperCase()+displayName.substring(1);
//			System.out.print("\""+displayName+"\",");
//		}
//		System.out.println("}");
//		System.out.println(Arrays.asList(Language.values()).indexOf(Language.FRENCH));
//		System.out.println(Arrays.asList(Language.values()).indexOf(Language.ENGLISH));
//		}

}
